package com.wpj.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.baomidou.mybatisplus.plugins.Page;
import com.github.tobato.fastdfs.domain.StorePath;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import com.wpj.common.entity.ResultEntity;
import com.wpj.entity.Goods;
import com.wpj.service.IGoodService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;

@Controller
@RequestMapping("/goods")
public class GoodsController {

    @Reference
    private IGoodService goodService;

    @RequestMapping("/getGoodsPage")
    public String getGoodsPage(Page<Goods> page, ModelMap map){
        page = goodService.getDubboPage(page);
        map.put("url", "goods/getGoodsPage");
        map.put("page",page);
        return "goods/goodsList";
    }

    @Autowired
    private FastFileStorageClient client;

    @Value("${upload.FdfsPath}")
    private String FdfsPath;

    private String uploadPath = "E:\\codeDevelop\\ideaDevelop\\springboot\\nz1904-shop\\shop-web\\user-web\\src\\main\\resources\\static\\upload";

    @RequestMapping("/uploadFile")
    @ResponseBody
    public String uploadFile(MultipartFile file){
        System.out.println("文件名："+ file.getOriginalFilename());
        FileOutputStream os = null;
        InputStream is = null;
        File opsFile = new File(uploadPath+ File.separator+file.getOriginalFilename());

        String fileName = file.getOriginalFilename();
        String fileExtName = fileName.substring(fileName.lastIndexOf(".")+1);
        StorePath storePath = null;
        try {
            storePath = client.uploadImageAndCrtThumbImage(file.getInputStream(), file.getSize(), fileExtName, null);

        } catch (IOException e) {
            e.printStackTrace();
        }
        return FdfsPath+storePath.getFullPath();
    }

    @RequestMapping(value = "/addGoods")
    @ResponseBody
    public ResultEntity addGoods(Goods goods){
        // 把商品添加数据库
        // 在这里主键回填不过来，所以要在service层添加
        goodService.insert(goods);
        return ResultEntity.SUCCESS();
    }
}
